import { createSlice, PayloadAction, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";
export interface UserDetailState {
  loading: boolean
  error: string | null
  jwt: string | null
}
const initialState: UserDetailState = {
  loading: false,
  error: null,
  jwt: null
}
export const signIn = createAsyncThunk('productDetail/getUserInfo', async (paramaters: {
  email: string,
  password: string,
},) => {
  const { data } = await axios.post(
    `http://123.56.149.216:8080/auth/login`, {
    email: paramaters.email,
    password: paramaters.password
  }
  );
  return data.token
})
export const userSlice = createSlice({
  name: 'productDetail',
  initialState,
  reducers: {
    layout(state) {
      state.jwt = null
      state.error = null
      state.loading = false
    }
  },
  extraReducers: {
    [signIn.pending.type]: (state) => {
      state.loading = true
    },
    [signIn.fulfilled.type]: (state, action: PayloadAction<any>) => {
      state.jwt = action.payload
      state.loading = false
      state.error = null
    },
    [signIn.rejected.type]: (state, action: PayloadAction<string | null>) => {
      state.loading = false
      state.error = action.payload
    }
  }
})